﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using KZ400B;
using System.Threading;

namespace KZ400BApp
{
    /// <summary>
    /// MultiAxleControl.xaml 的交互逻辑
    /// </summary>
    public partial class MultiAxleControl : Window
    {
        AxleToZeroManageV2 m_toZeroManager = null;
        public MultiAxleControl()
        {
            InitializeComponent();
            this.Unloaded += new RoutedEventHandler(MultiAxleControl_Unloaded);
            //PositionCacheManager.OnAxlePostionChange += new AxlePositionChange(AxleManager_OnAxlePostionChange);
            //AxleManager.OnAxleActionResponse += new AxleActionResponse(AxleManager_OnAxleActionResponse);
            this.DataContext = PositionCacheManager.AxleStates;
            m_toZeroManager = new AxleToZeroManageV2();

            m_toZeroManager.Regist(AxleCacheManager.AxleList);
           
            
        }

        void MultiAxleControl_Unloaded(object sender, RoutedEventArgs e)
        {
            //PositionCacheManager.OnAxlePostionChange -= new AxlePositionChange(AxleManager_OnAxlePostionChange);
            //AxleManager.OnAxleActionResponse -= new AxleActionResponse(AxleManager_OnAxleActionResponse);
            m_toZeroManager.UnRegist(); 
        }

        //void AxleManager_OnAxleActionResponse(string axleName, Axle axle, AxleActions action, bool success,string message)
        //{
        //    Console.WriteLine("get axle action {0} {1} ", axleName, action.ToString());
        //    //if (
        //    //action == AxleActions.RunFinish
        //    //|| action == AxleActions.StopFinish
        //    //)
        //    //{
        //    //    AxleManager.QueryPosition(axleName);
        //    //}
        //}

        void invokePositionChange(KZ400B.Controls.AxleRunStateForMulti control, string axleName, double position)
        {
            if (control != null && !string.IsNullOrEmpty(axleName))
            {
                control.Dispatcher.Invoke(new Action(delegate()
                {
                    //control.AxlePosition = position;
                    PositionCacheManager.ChangePosition(axleName, position, true);
                }
                ));
            }
        }

        void AxleManager_OnAxlePostionChange( string axleName, Axle axle, double position,bool ack)
        {
            if (!ack)
            { 
                
            }

            if (axleName.Equals("X"))
            {
                //xControl.AxlePosition = postion;
                invokePositionChange(xControl, axleName, position);
            }
            else if (axleName.Equals("Y"))
            {
                //yControl.AxlePosition = postion;
                invokePositionChange(yControl, axleName, position);
            }
            else if (axleName.Equals("Z"))
            {
                //zControl.AxlePosition = postion;
                invokePositionChange(zControl, axleName, position);
            }
            else if (axleName.Equals("T"))
            {
                //tControl.AxlePosition = postion;
                invokePositionChange(tControl, axleName, position);
            }
            else if (axleName.Equals("U"))
            {
                //uControl.AxlePosition = postion;
                invokePositionChange(uControl, axleName, position);
            }
            else if (axleName.Equals("W"))
            {
                //wControl.AxlePosition = postion;
                invokePositionChange(wControl, axleName, position);
            }
        }

        private void allStop()
        {
            if (!AxleManager.IsOpen)
            {
                KZ400B.Controls.StateMsgManager.addOneState("未连接,请检查连接状态!");
                return;
            }
            //AxleManager.Stop(getCheckedList());
            List<string> sList = getCheckedList();
            if (sList != null)
            {
                foreach (string an in sList)
                {
                    AxleManager.Stop(an);
                    Thread.Sleep(100);
                }
            }
        }

        private void btnAllStop_Click(object sender, RoutedEventArgs e)
        {
            //if (!AxleManager.IsOpen)
            //{
            //    KZ400B.Controls.StateMsgManager.addOneState("未连接,请检查连接状态!");
            //    return;
            //}
            ////AxleManager.Stop(getCheckedList());
            //List<string> sList = getCheckedList();
            //if (sList != null)
            //{
            //    foreach (string an in sList)
            //    {
            //        AxleManager.Stop(an);
            //        Thread.Sleep(100);
            //    }
            //}
            allStop();
        }

        private void btnStart_Click(object sender, RoutedEventArgs e)
        {
            if (!AxleManager.IsOpen) {
                KZ400B.Controls.StateMsgManager.addOneState("未连接,请检查连接状态!");
                return;
            }
            //AxleManager.Run(getCheckedList(true));
            List<string> executeList = getCheckedList();
            List<string> toZeroList = new List<string>();
            //bool isTO = false;
            //int timeout = 60000;
            //int tmpto = 0;

            try
            {
                KZ400B.Controls.StateMsgManager.addOneState("归零检查中!");
                //to zero
                if (executeList != null && executeList.Count > 0)
                {
                    foreach (string aName in executeList)
                    {
                        if (!m_toZeroManager.IsToZeroReady(aName))
                        //if(AxleCacheManager.AxleList.ContainsKey(aName) 
                        //    && !AxleCacheManager.AxleList[aName].IsToZeroed
                        //    )
                        {
                            AxleManager.ToZeroIM(aName
                                , AxleCacheManager.AxleList[aName].getTozeroPwm(
                                AxleCacheManager.AxleList[aName].TozeroSpeed
                                ));
                            //toZeroList.Add(aName);
                            //Thread.Sleep(200);
                        }
                    }
                }

                //wait for all axle tozero success
                //if (toZeroList != null && toZeroList.Count > 0)
                //{

                //    while (toZeroList.Count > 0)
                //    {
                //        int tzs = 0;
                //        foreach (string aName in toZeroList)
                //        {
                //            if (m_toZeroManager.IsToZeroReady(aName))
                //            {
                //                tzs++;
                //            }
                //            else if (m_toZeroManager.IsToZeroError(aName))
                //            {
                //                KZ400B.Controls.StateMsgManager.addOneState("归零发生错误!");
                //                return;
                //            }
                //        }
                //        if (tzs == toZeroList.Count)
                //        {
                //            break;
                //        }
                //        else { Thread.Sleep(50); tmpto += 50; }
                //        if (tmpto > timeout)
                //        {
                //            KZ400B.Controls.StateMsgManager.addOneState("归零超时!");
                //            isTO = true;
                //            break;

                //        }
                //    }
                //}
                //if (isTO) return;

                //reset all axle tozero action
                if (toZeroList != null && toZeroList.Count > 0)
                {
                    foreach (string aName in toZeroList)
                    {
                        m_toZeroManager.ResetAction(aName);
                    }

                }


            }
            catch (Exception EX)
            {
                Console.WriteLine(EX.Message);
            }
            Thread.Sleep(100);
            KZ400B.Controls.StateMsgManager.addOneState("归零检查完毕!");
            getCheckedList(true);
        }

        private List<string> getCheckedList()
        {
            return getCheckedList(false);
        }
        private List<string> getCheckedList(bool sendsetting)
        {
            List<string> axleList = new List<string>();
            List<string> rList = new List<string>();
            List<KZ400B.Controls.AxleRunStateForMulti> controlList = new List<KZ400B.Controls.AxleRunStateForMulti>();
            if (xControl.IsChecked)
            {
                controlList.Add(xControl);
                axleList.Add(xControl.AxleName);
                //if (sendsetting)
                //{
                //    xControl.SendSetting();
                //}
                //MySetting.setUnionStoreAxleValue(xControl.AxleName, xControl.TargetPostion);
            }

            if (yControl.IsChecked)
            {
                controlList.Add(yControl);
                axleList.Add(yControl.AxleName);
                //if (sendsetting)
                //{
                //    yControl.SendSetting();
                //}
                //MySetting.setUnionStoreAxleValue(yControl.AxleName, yControl.TargetPostion);
            }

            if (zControl.IsChecked)
            {
                controlList.Add(zControl);
                axleList.Add(zControl.AxleName);
                //if (sendsetting)
                //{
                //    zControl.SendSetting();
                //}
                //MySetting.setUnionStoreAxleValue(zControl.AxleName, zControl.TargetPostion);
            }

            if (tControl.IsChecked)
            {
                controlList.Add(tControl);
                axleList.Add(tControl.AxleName);
                //if (sendsetting)
                //{
                //    tControl.SendSetting();
                //}
                //MySetting.setUnionStoreAxleValue(tControl.AxleName, tControl.TargetPostion);
            }

            if (uControl.IsChecked)
            {
                controlList.Add(uControl);
                axleList.Add(uControl.AxleName);
                //if (sendsetting)
                //{
                //    uControl.SendSetting();
                //}
                //MySetting.setUnionStoreAxleValue(uControl.AxleName, uControl.TargetPostion);
            }

            if (wControl.IsChecked)
            {
                controlList.Add(wControl);
                axleList.Add(wControl.AxleName);
                //if (sendsetting)
                //{
                //    wControl.SendSetting();
                //}
                //MySetting.setUnionStoreAxleValue(wControl.AxleName,wControl.TargetPostion);
            }
            bool rst = true;
            if (sendsetting)
            { 
                foreach(KZ400B.Controls.AxleRunStateForMulti ct in controlList)
                {
                    double step = 0.0F;
                    rst &= ct.SendSetting(ref step);
                    if (!rst)
                    {
                        KZ400B.Controls.StateMsgManager.addOneState(
                            string.Format("{0}轴参数设置错误",ct.AxleName)
                            );
                        break;
                    }
                    if (rst && step != 0.0F)
                    {
                        rList.Add(ct.AxleName);
                    }
                }
                if (!rst)
                {
                    controlList.Clear();
                    axleList.Clear();
                }
                else
                {
                    foreach (string aName in rList)
                    {
                        rst &= AxleManager.Run(aName);
                        Thread.Sleep(100);
                    }
                }
            }
            return axleList;
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            allStop();
            this.Close();
        }
    }
}
